#include "ColorPalettesElement.h"
#include <QTimer>
#include <QWidget>
ColorPalettesElement::ColorPalettesElement(const QString& iPath, const int& index,const bool& bPreview ,const QString& name, const QString& cmdKey)
	:LeafElement(iPath, index, cmdKey), _name(name), _textWidth(200), _drawLength(name.length()),
	_timer(nullptr), _isDrawFlag(false), _timerInterval(500), _bSelected(false),_bPreview(bPreview)
{


}

ColorPalettesElement::~ColorPalettesElement()
{
	if (_timer != nullptr) {
		delete _timer;
		_timer = nullptr;
	}
}

void ColorPalettesElement::setRect(const QRect& rect)
{

	if (rect.isEmpty())
	{
		if (_timer != nullptr && _timer->isActive())
		{
			_timer->stop();
		}
	}
	UIElement::setRect(rect);
}

void ColorPalettesElement::drawElement(QWidget* widget, QPainter* painter, bool bSelected, const QRect& rect)
{
	//initTimer(widget);
	_isDrawFlag = true;
	_bSelected = bSelected;
	setRect(rect);
	drawIcon(painter);
	drawName(painter);
	_isDrawFlag = false;
}

void ColorPalettesElement::drawName(QPainter* painter)
{
	if (_drawLength > 0&& _bSelected) {
		QFont font;
		font.setPixelSize(30);
		font.setFamily("Source Han Sans K");
		painter->setFont(font);
		QPen pen(QColor(10, 132, 255));
		painter->setPen(pen);
		QFontMetrics metrics(font);
		QString text(getTranslate(_name));

		int w = metrics.width(text);
		QRect textRect(_rect.topRight() + QPoint(8, 42), QSize(_textWidth, metrics.height()));
		if (w > textRect.width() && _timer != nullptr) {
			if (!_timer->isActive()) {
				_timer->start(_timerInterval);
			}
		}
		painter->drawText(textRect, Qt::AlignLeft | Qt::AlignVCenter, text.right(_drawLength));
	}
}

void ColorPalettesElement::drawIcon(QPainter* painter)
{
	QRect imageRect;

	QString iconPath = _iconPath + (_bSelected ? QString("/s/%1s.png").arg(_index) : QString("/n/%1n.png").arg(_index));
	QPixmap pixmap(iconPath);
	if (pixmap.isNull()) {
		return;
	}
	imageRect = QRect(_rect.topLeft(), pixmap.size());
	painter->drawPixmap(imageRect, pixmap);
}

void ColorPalettesElement::initTimer(QWidget* widget)
{
	if (widget != nullptr && _timer == nullptr) {
		_timer = new QTimer(widget);
		QObject::connect(_timer, &QTimer::timeout, [&]() {
			this->slotTimer();
			});
	}
}

void ColorPalettesElement::slotTimer()
{
	if (_isDrawFlag)
	{
		return;
	}
	QWidget* widget = qobject_cast<QWidget*>(_timer->parent());
	_drawLength--;
	if (_drawLength <= 0) {
		_drawLength = _name.length();
	}
	widget->update(_rect);
}
